﻿using CompanyHubServer.DAL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CompanyHubServer.Controllers
{
    public class TokenController : Controller
    {
        private HubContext db = new HubContext();

        public ActionResult Index()
        {
            var tokens = db.AppTokens.OrderByDescending(t => t.UploadedDT);

            return View(tokens);
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {

            if (file.ContentLength > 0)
            {
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Downloads/"), fileName);
                file.SaveAs(path);

                var curToken = db.AppTokens.Where(t => t.IsActive).FirstOrDefault();
                if (curToken != null)
                    curToken.IsActive = false;

                var token = db.AppTokens.Create();
                //token.Id = db.AppTokens.Count() + 1;
                token.UploadedDT = DateTime.Now;
                token.SourceUri = fileName;
                token.IsActive = true;
                token.Expires = DateTime.Now;

                db.AppTokens.Add(token);

                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
